﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using NCP.Recruiting.ApplicationServices.Interfaces;
using NCP.Recruiting.WebApp.Models;
using NCP.Recruiting.ApplicationServices.Shared;
using NCP.Recruiting.ApplicationServices.Messaging.Candidates;
using NCP.Recruiting.ApplicationServices.ViewModels;
using NCP.Infrastructure.Common;
using NCP.Recruiting.Web.Framework.Controllers;
using NCP.Recruiting.ApplicationServices.Messaging.Settings;

namespace NCP.Recruiting.WebApp.Controllers
{
    public class CandidateController : AuthorizedController
    {
        #region Const
        private const int _pageSize = 15;
        private const String _dateFormat = "yyyy/MM/dd";
        private const String _defaultKeyword = "请输入职位名称";
        #endregion

        private readonly ICandidateAppService _candidateAppService;
        private readonly IReceiptAppService _receiptAppService;
        private readonly IInterviewAppService _interviewAppService;
        private readonly ISettingAppService _settingAppService;
        public CandidateController(ICompanyAppService companyAppService,
            ICandidateAppService candidateAppService,
            IReceiptAppService receiptAppService,
            IInterviewAppService interviewAppService,
            ISettingAppService settingAppService)
            : base(companyAppService)
        {
            this._candidateAppService = candidateAppService;
            this._receiptAppService = receiptAppService;
            this._interviewAppService = interviewAppService;
            this._settingAppService = settingAppService;
        }

        #region List
        public ViewResult RecoverList(PagingFilteringModel command)
        {
            //初始化分页组件
            if (command.PageSize <= 0)
            {
                command.PageSize = _pageSize;
            }
            if (command.PageNumber <= 0)
            {
                command.PageNumber = 1;
            }

            var request = new SearchCandidateListRequest()
            {
                CandidateQueryStatus = CandidateQueryStatus.Deleted,
                CompanyId = base.CurrentUserId,
                PageIndex = command.PageIndex,
                PageSize = command.PageSize,
                Keyword = ""
            };

            var response = _candidateAppService.SearchList(request);
            var bindItem = new CandidateListViewModel()
            {
                CandidateList = response.CandidateList,
                PagingFilteringContext = new PagingFilteringModel<CandidateItemViewModel>(response.CandidateList),
            };
            return View(bindItem);
        }

        public ViewResult List(PagingFilteringModel command,
            CandidateQueryStatus queryStatus = CandidateQueryStatus.All,
            string keyword = "")
        {
            ResetSearchCommand(command, ref keyword);

            var request = new SearchCandidateListRequest()
            {
                CandidateQueryStatus = queryStatus,
                CompanyId = base.CurrentUserId,
                Keyword = keyword,
                PageIndex = command.PageIndex,
                PageSize = command.PageSize
            };

            var response = _candidateAppService.SearchList(request);
            var bindItem = new CandidateListViewModel()
            {
                CandidateList = response.CandidateList,
                PagingFilteringContext = new PagingFilteringModel<CandidateItemViewModel>(response.CandidateList),
                CandidateQueryStatus = queryStatus,
                Keyword = keyword,
            };

            SetMessageBind();
            return View(bindItem);
        }
        #endregion

        #region Recover
        [HttpPost]
        public ActionResult Reduction(Guid id)
        {
            var response = _candidateAppService.RecoverByIds(new RecoverRequest
                {
                    RecoverIds = new List<Guid>() { id }
                });
            return Json(response.IsSuccess);
        }

        [HttpPost]
        [ActionName("RecoverList")]
        [FormValueRequired("RecoverSelected")]
        public ActionResult RecoverSelected(CandidateListViewModel model)
        {
            _candidateAppService.RecoverByIds(new RecoverRequest()
            {
                RecoverIds = model.CandidateList.Where(s => s.IsChecked).Select(s => s.Id).ToList()
            });
            return RedirectToAction("RecoverList");
        }
        #endregion

        #region Delete
        [HttpPost]
        [ActionName("List")]
        [FormValueRequired("Delete")]
        public ActionResult Delete(Guid id, CandidateQueryStatus queryStatus = CandidateQueryStatus.All,
            string keyword = "")
        {
            _candidateAppService.DeleteByIds(new DeleteRequest()
                {
                    DeleteIds = new List<Guid>() { id }
                });
            return RedirectToAction("List", new { queryStatus = queryStatus, keyword = keyword });
        }

        [HttpPost]
        [ActionName("List")]
        [FormValueRequired("DeleteSelected")]
        public ActionResult DeleteSelected(CandidateListViewModel model, CandidateQueryStatus queryStatus = CandidateQueryStatus.All,
            string keyword = "")
        {
            _candidateAppService.DeleteByIds(new DeleteRequest()
            {
                DeleteIds = model.CandidateList.Where(s => s.IsChecked).Select(s => s.Id).ToList()
            });
            return RedirectToAction("List", new { queryStatus = queryStatus, keyword = keyword });
        }
        #endregion

        #region Set Message Bind
        private void SetMessageBind()
        {
            var request = new GetMessageTemplateRequest(base.CurrentUserId);
            var response = _settingAppService.GetMessageTemplates(request);
            Func<IEnumerable<MessageTemplateViewModel>, SelectList> func = (inputList) =>
                {
                    var list = inputList.ToList();
                    list.Insert(0, new MessageTemplateViewModel { Id = Guid.Empty, Subject = "请选择" });
                    var result = new SelectList(list, "Id", "Subject");
                    return result;
                };
            ViewBag.ReplyTemplates = func(response.MessageTemplates
                .Where(s => s.Purpose == 0));
            ViewBag.InterviewTemplates = ViewBag.ReplyTemplates = func(response.MessageTemplates
                .Where(s => s.Purpose == 1));
        }
        #endregion

        #region Get Template Content
        [HttpPost]
        public ActionResult GetTemplateContent(MessageTemplateViewModel model)
        {
            var request = new GetMessageTemplateRequest(model.Id);
            var response = _settingAppService.GetMessageTemplate(request);
            if (response.Exception != null)
            {
                return Json("");
            }
            return Json(response.Properties.TemplateContent);
        }
        #endregion

        #region ResumeReply
        [HttpPost]
        public ActionResult ResumeReply(ResumeReplyModel model)
        {
            var request = new ResumeReplyRequest
            {
                CompanyId = base.CurrentUserId,
                Jobseekers = model.Jobseekers,
                Message = model.Message,
                Subject = model.Subject,
                Id = model.Id
            };
            var response = _receiptAppService.ResumeReply(request);
            return Json(response.IsSuccess);
        }
        #endregion

        #region InvitedToInterview
        [HttpPost]
        public ActionResult InvitedToInterview(InterviewModel model)
        {
            var request = new InvitedToInterviewRequest
            {
                Body = model.InterviewBody,
                CompanyId = base.CurrentUserId,
                Date = model.InterviewDate.Value,
                Jobseekers = model.InterviewJobseekers,
                Location = model.InterviewLocation,
                Subject = model.InterviewSubject,
                Time = model.InterviewTime,
                Id = model.Id
            };
            var reponse = _interviewAppService.InvitedToInterview(request);
            return Json(reponse.IsSuccess);
        }
        #endregion

        #region ResetSearchCommand
        private static void ResetSearchCommand(PagingFilteringModel command, ref string keyword)
        {
            //初始化分页组件
            if (command.PageSize <= 0)
            {
                command.PageSize = _pageSize;
            }
            if (command.PageNumber <= 0)
            {
                command.PageNumber = 1;
            }

            //如果关键字等于默认关键字则置空
            if (keyword.Equals(_defaultKeyword))
            {
                keyword = String.Empty;
            }
        }
        #endregion

        #region Priview
        public ActionResult Priview(Guid id,
            CandidateQueryStatus queryStatus = CandidateQueryStatus.All,
            string keyword = "", string idList = "")
        {
            var model = GetResumePrviewModel(id, queryStatus, keyword, idList);
            SetMessageBind();
            return View(model);
        }

        [HttpPost]
        [ActionName("List")]
        [FormValueRequired("PriviewSelected")]
        public ActionResult PriviewSelected(CandidateListViewModel model, CandidateQueryStatus queryStatus = CandidateQueryStatus.All,
            string keyword = "")
        {
            var selectIds = model.CandidateList.Where(s => s.IsChecked).Select(s => s.Id).ToList();
            return RedirectToAction("Priview", new
            {
                id = selectIds.FirstOrDefault(),
                queryStatus = queryStatus,
                keyword = keyword,
                idList = string.Join(",", selectIds.Select(s => s.ToString()).ToArray())
            });
        }
        #endregion

        #region SetIsReadLetter
        [HttpPost]
        public ActionResult SetIsReadLetter(ResumeReplyModel model)
        {
            var request = new SetIsReadLetterRequest { Id = model.Id };
            var response = _candidateAppService.SetIsReadletter(request);

            return Json(response.IsScussess);
        }
        #endregion

        #region Change id and model
        private static List<Guid> ChangeIds(string idList)
        {
            return (idList ?? string.Empty)
                .Split(',')
                .Where(s => !string.IsNullOrWhiteSpace(s))
                .Select(s => Guid.Parse(s))
                .ToList();
        }

        private ResumePrviewModel GetResumePrviewModel(Guid id,
            CandidateQueryStatus queryStatus = CandidateQueryStatus.All,
            string keyword = "", string idList = "")
        {
            //如果关键字等于默认关键字则置空
            if (_defaultKeyword.Equals(keyword))
            {
                keyword = String.Empty;
            }

            var request = new ResumePrviewRequest
            {
                CandidateQueryStatus = queryStatus,
                CompanyId = CurrentUserId,
                CurrentId = id,
                Keyword = keyword ?? string.Empty,
                CandidateIdList = ChangeIds(idList)
            };
            var response = _candidateAppService.GetPrviewItem(request);

            return new ResumePrviewModel
            {
                CandidateQueryStatus = queryStatus,
                CurrentResumeItem = response.CurrentResume,
                Keyword = keyword ?? string.Empty,
                CurrentCandidateItem = response.CurrentCandidate,
                InterviewModel = response.InterviewModel,
                ResumeReplyModel = response.ResumeReplyModel,
                CandidateIdList = idList ?? string.Empty,
                CurrentItemIndex = response.CurrentItemIndex
            };
        }
        #endregion

        #region CandidatePrviewSave
        [HttpPost]
        public ActionResult CandidatePrviewSave(CandidatePrviewViewModel module)
        {
            var request = new PrviewSaveRequest
            {
                CandidatePrviewViewModel = module,
                CompanyId = base.CurrentUserId
            };
            var response = _candidateAppService.PrviewSave(request);
            return Json(response);
        }
        #endregion

        #region Prve Next
        [HttpPost]
        public ActionResult PrveOrNext(ResumePrviewModel model)
        {
            var request = new PrveNextRequest
                {
                    CandidateIdList = ChangeIds(model.CandidateIdList),
                    CandidateQueryStatus = model.CandidateQueryStatus,
                    CompanyId = CurrentUserId,
                    CurrentItemIndex = model.CurrentItemIndex,
                    IsPrev = model.Type == "0",
                    Keyword = model.Keyword ?? string.Empty
                };
            var response = _candidateAppService.GetPrveOrNextId(request);

            return RedirectToAction("Priview", new
            {
                id = response.CurrentId,
                queryStatus = model.CandidateQueryStatus,
                keyword = model.Keyword ?? string.Empty,
                idList = model.CandidateIdList
            });
        }
        #endregion
    }
}
